package com.knife.oauth.security.customer.handler;

import com.knife.common.exception.CommonException;
import com.knife.oauth.app.service.IamUserRoleService;
import com.knife.oauth.constants.KnifeOauthConstant;
import com.knife.oauth.domain.entity.IamMemberRole;
import com.knife.oauth.domain.entity.IamUser;
import com.knife.oauth.domain.service.impl.DefaultKnifeUserDetailsBuilder;
import com.knife.redis.KnifeRedisHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 通过实现{@link UserDetailsService}来实现自定义认证
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2021年12月02日 星期四 9:17 上午
 * @description
 * @since 1.0
 */
@Service
public class KnifeUserDetailsServiceImpl implements UserDetailsService, KnifeOauthConstant {


    @Autowired
    private IamUserRoleService userRoleService;

    @Autowired
    private KnifeRedisHelper knifeRedisHelper;

    @Autowired
    private DefaultKnifeUserDetailsBuilder defaultKnifeUserDetailsBuilder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        knifeRedisHelper.setCurrentDatabase(REDIS_DB);
        try {
            IamUser tUser = userRoleService.selectByUserName(s);
            if (Objects.isNull(tUser)){
                throw new CommonException("请检查用户名是否正确");
            }
            List<IamMemberRole> tUserRoles = userRoleService.listIamMemberRoleByUserName(s);
            // 将用户信息缓存
            tUser.setIamMemberRoleList(tUserRoles);
            knifeRedisHelper.strSet(tokenUserKey(tUser.getId().toString()), knifeRedisHelper.toJson(tUser));
            return defaultKnifeUserDetailsBuilder.changeToUser(tUser,tUserRoles);
        } finally {
            knifeRedisHelper.clearCurrentDatabase();
        }
    }

}
